package play.cnblog.cli.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import play.cnblog.cli.model.Blog;
import play.cnblog.cli.service.BlogService;

public class BlogServiceImpl implements BlogService {

    private static final int COLUMN_MIN = 2;
    private static final int BLOG_INDEX = 0;
    private static final int TITLE_INDEX = 1;
    private static final int CATEGORIES_INDEX = 2;
    private static final int KEYWORDS_INDEX = 3;

    @Override
    public Blog parseFile(String filePath) {
        return buildBlog(filePath);
    }

    @Override
    public void writeFile(Blog blog) {
    }

    private Blog buildBlog(String filePath) {
        List<String> contents;
        try {
            contents = Files.readAllLines(getPath(filePath));
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        String firstLine = contents.get(0);
        if (Objects.isNull(firstLine)) {
            throw new RuntimeException("第一行没有相关信息");
        }
        String[] info = firstLine.split("\\|");
        if (info.length < COLUMN_MIN) {
            throw new RuntimeException("行首信息缺失");
        }
        String bookDiv = book(filePath);
        if (StringUtils.isNotBlank(bookDiv)) {
            contents.add(bookDiv);
        }
        Blog blog = new Blog();
        blog.setPostid(info[BLOG_INDEX]);
        blog.setTitle(info[TITLE_INDEX]);
        blog.setMt_keywords(keywords(info));
        blog.setCategories(categories(info));
        blog.setDescription(content(contents));
        return blog;
    }

    private Path getPath(String filePath) {
        return Paths.get(filePath);
    }

    private List<String> categories(String[] info) {
        if (info.length - 1 - CATEGORIES_INDEX < 0) {
            return null;
        }
        String[] tmpCategories = info[CATEGORIES_INDEX].split(",");
        List<String> categories = new ArrayList<>(tmpCategories.length + 1);
        categories.add("[Markdown]");
        for (String tmp : tmpCategories) {
            categories.add("[随笔分类]" + tmp.trim());
        }
        return categories;
    }

    private String keywords(String[] info) {
        if (info.length - KEYWORDS_INDEX < 0) {
            return null;
        }
        return info[KEYWORDS_INDEX];
    }

    private String content(List<String> contentList) {
        contentList.remove(0);
        StringBuilder blogContent = new StringBuilder();
        for (String line : contentList) {
            blogContent.append(line).append("\n");
        }
        return blogContent.toString();
    }

    private String book(String filePath) {
        String bookFileName = "book.md";
        File file = new File(filePath);
        if (bookFileName.equalsIgnoreCase(file.getName())) {
            return null;
        }
        String path;
        if (file.isFile()) {
            path = file.getParent();
        }
        else {
            path = filePath;
        }
        File bookFile = new File(path, bookFileName);
        if (!bookFile.exists()) {
            return null;
        }
        List<String> contents;
        try {
            contents = Files.readAllLines(getPath(bookFile.getPath()));
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        String firstLine = contents.get(0);
        if (Objects.isNull(firstLine)) {
            throw new RuntimeException("第一行没有相关信息");
        }
        String[] info = firstLine.split("\\|");
        if (info.length < COLUMN_MIN) {
            throw new RuntimeException("行首信息缺失");
        }
        String bookPostId = info[BLOG_INDEX];

        return
            "<div id=\"bookTag\" style=\"display:none\">" + bookPostId + "</div>";
    }

    // TODO 写入文件
    public void write() throws IOException {
        Blog blog = new Blog();
        String outDir = "target/testoutput/";
        String fileName = "GET.md";
        String blogId = "12567518";
        Files.createDirectory(Paths.get(outDir));
        String targetFile = outDir + fileName;
        OutputStream out = new FileOutputStream(targetFile);

        StringBuilder sb = new StringBuilder();
        sb
            .append(blog.getPostid()).append("|")
            .append(blog.getTitle()).append("|")
            .append(String.join(",", blog.getCategories())).append("|")
            .append(blog.getMt_keywords()).append("\n\n");
        out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
        out.write(blog.getDescription().getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
